package cn.web.servlet;

import cn.domain.User;
import cn.service.Userservice;
import cn.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;


import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.FileStore;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      //1.设置编码
        request.setCharacterEncoding("utf-8");
        //2.获取数据
        String verifycode = request.getParameter("verifycode");//获取用户填写的验证码
        HttpSession session=request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");//用完就删掉，确保一次性

        if(!checkcode_server.equalsIgnoreCase(verifycode)){
            //当验证码不正确
            request.setAttribute("login_respon","验证码错误");
            request.getRequestDispatcher("/login.jsp").forward(request, response);//跳转
            return;
        }

        Map<String,String[]>map=request.getParameterMap();
        //2.1获取验证码
        User user =new User();

        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


        Userservice service=new UserServiceImpl();
        User user1 = service.FindUserByUsernameAndPassword(user);
        if(user1 != null){
            System.out.println(user1);
            System.out.println("不为空");
            session.setAttribute("user",user1);
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }else{
            request.setAttribute("login_respon","用户名或者密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }

    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            this.doGet(request, response);

    }
}
